package org.example.erp.web.handler;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.example.erp.controller.DataResult;
import org.example.erp.utils.JwtUtil;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.time.Instant;
import java.util.HashMap;
import java.util.Map;
/*
 * @Date 2024-10-09
 * @Author 28254
 * @ClassName MyAuthenticationSuccessHandler
 * 处理登录认证成功类
*/
@Component
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException{
        // 设置编码方式
        response.setContentType("application/json;charset=utf-8");
        response.setCharacterEncoding("utf-8");

        // 查询数据并且生成jwt令牌
        ObjectMapper mapper = new ObjectMapper();
        Map<String,Object> map = new HashMap<>();
        map.put("username",authentication.getName());
        String jwt = JwtUtil.getJwt(map);
        // 创建响应对象并且以json格式返回出去
        String result = mapper.writeValueAsString(new DataResult(200,jwt,"登录成功", Instant.now().toEpochMilli()));
        response.getWriter().println(result);
    }
}
